<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/10/20
 * Time: 11:21
 */

namespace app\common\mysic\bonus;

use app\common\model\User;
use app\common\mysic\MysicBase;
use app\common\model\divide\Refund;
use think\Exception;
use think\Model;

class BonusRefundOp extends MysicBase implements BonusRefundInterface
{
    /**
     * @var Refund 分红退款失败记录表
     */
    protected $model;
    protected $userOrder;
    protected $bonusSetting;
    protected $bonus;
    protected $issue;
    protected $wxResponse;
    protected $userModel;
    public function setUserModel(User $userModel)
    {
        $this->userModel = $userModel;
        return $this;
    }
    public function setModel(Model $model)
    {
        if(!($model instanceof Refund)) {
            throw new Exception('退款失败表模型传参错误');
        }
        $this->model = $model;
        return $this;
    }
    public function setWxRefundResponse(array $wxResponse)
    {
        $this->wxResponse = $wxResponse;
        return $this;
    }
    public function setUserOrder(Model $order)
    {
        $this->userOrder = $order;
        return $this;
    }
    public function setBonusSettingEntity($bonusSetting)
    {
        $this->bonusSetting = $bonusSetting;
        return $this;
    }
    public function setBonus($bonus)
    {
        $this->bonus = $bonus;
        return $this;
    }

    public function create()
    {
        $account = $this->userModel->where(['user_id' => $this->userOrder->user_id, 'wxapp_id' => $this->userOrder->wxapp_id])->value('open_id');
        $this->model->refund_id = null;
        $this->model->user_id = $this->userOrder->user_id;
        $this->model->account = $account;
        $this->model->order_no = $this->userOrder->order_no;
        $this->model->wxapp_id = $this->userOrder->wxapp_id;
        $this->model->amount = $this->bonus;
        $this->model->payment = $this->userOrder->pay_price;
        $this->model->periods_num = $this->bonusSetting->periods_num;
        $this->model->transaction_id = $this->userOrder->transaction_id;
        $this->model->top_limit = bcmul(strval($this->userOrder->pay_price), bcdiv(strval($this->bonusSetting->upline), '100'),2);
        $this->model->type = 0;
        $this->model->status = 2;
        $this->model->fail_reason = $this->wxResponse['err_code_des'] ?? [];
        $this->model->create_time = \time();
        $this->model->update_time = \time();
        $this->model->isUpdate(false);
        $ret = $this->model->save();
        if(!$ret) {
            return false;
        }
        return true;
    }
}